package com.flycms.modules.template.utils;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * @author sun-kaifei
 * @version 1.0 <br/>
 * @email 79678111@qq.com
 * @Date: 23:34 2019/8/26
 */


public class StringTemplateLoader implements TemplateLoader {

    private String template;

    public StringTemplateLoader(String template) {
        this.template = template;
        if (template == null) {
            this.template = "";
        }
    }

    public Object findTemplateSource(String name) throws IOException {
        return new StringReader(template);
    }

    @Override
    public long getLastModified(Object templateSource) {
        return 0;
    }

    public Reader getReader(Object templateSource, String encoding)
            throws IOException {
        return (Reader) templateSource;
    }

    public void closeTemplateSource(Object templateSource) throws IOException {
        ((StringReader) templateSource).close();
    }


    public static void main(String[] args) throws Exception {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setTemplateLoader(new StringTemplateLoader("..Hello,${user}!"));
        Map root = new HashMap();
        root.put("user", "Jack");
        StringWriter writer = new StringWriter();

        long start = System.currentTimeMillis();

        Template template = cfg.getTemplate("");
        template.process(root, writer);

        System.out.println(System.currentTimeMillis() - start);
        System.out.println(writer.toString());
    }


}
